package com.example.myfirstapp;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.format.Time;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

//test
public class MainActivity extends Activity {
	// Score variables
	double score = 0; // This is always increasing, unless a user presses a
						// wrong button, in which case, it goes to 0
	double modifier = 0; // The modifier is what is being added to the score
							// each button press. Uses elapsed time and time
							// difference
	File file; // Used for saving local high scores on a phone.
	FileWriter fw;
	BufferedWriter bw;
	PrintWriter pw; // we might only need fw and bw

	// Time variables
	// Maintain a seconds and milliseconds version of start, previous, current
	// and elapsed time
	double startTime_ms; // start time in milli-seconds of type double
	double startTime_s; // comment on startTime_ in seconds
	double previousTime_ms; // preveioustime_ms of type double
	double previousTime_s; // previous time type double
	double currentTime_ms; // current time type double
	double currentTime_s; // current time type double
	double elapsedTime_ms; // The difference between the current time and the
							// start time
	double elapsedTime_s;
	double timeDiff_ms; // The difference between the current time and the
						// previous time
	double timeDiff_s; // variable of type double

	// Color variables
	String nextColor_s;
	int nextColor; // This is the integer equivalent of nextColor_s
	int textColor; // This is the color to print the string out in

	// Button resizing variables
	int screenWidth; // screen width type int
	int screenHeight; // screen width type int

	public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
	private static final int WRAP_CONTENT = 0;

	Timer myTimer; // time declaration
	private int mInterval = 1000; // initialize mInterval to 1000
	private Handler mHandler; // variable of type private
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Display display = getWindowManager().getDefaultDisplay(); // display display = function to display window

		screenWidth = display.getWidth();
		screenHeight = 1; // display.getHeight();
		
		writeToFile (111); // takes user input and writes to file?
		writeToFile (222); 
		
		resetTime(); 
		updateColor();
		updateScore();
		mHandler = new Handler();
		startRepeatingTask();
	}
void getDebugFlags()
{
	
	
}
	
public int getRenderMode ()
{
	return mInterval;
	
	// gets the current 
	// rendering mode of the squares program
	// this returns the current rendering mode

}

	Runnable mStatusChecker = new Runnable() {
		@Override
		public void run() {
			//updateStatus(); // this function can change value of mInterval.
			updateTime();
			mHandler.postDelayed(mStatusChecker, mInterval);
		}
	};

	void startRepeatingTask() { // void start repeating tasks run the mstatus checker
		mStatusChecker.run();
	}

	void stopRepeatingTask() { // another stopRepeatingTask function to remove callbacks
		mHandler.removeCallbacks(mStatusChecker);
	}

	public class Timer extends AsyncTask<Void, Void, Void> { // the public class timer
		protected Void doInBackground (Void... args) {	
			updateTime(); // update the time used for game 
			return null;
		}

		public void schedule(TimerTask timerTask, int i) {
			// TODO Auto-generated method stub
			
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu); // this is to create a menu for the game? -- jonathan
		return true;
	}

	// This will be used for loading high scores
	// We can also save times, and full games (so we can do replays perhaps)
	// creating replay would be neat, not sure how that would be implemented though
	public void writeToFile(double score) {
		try {
			if (file == null) {
				Time today = new Time(Time.getCurrentTimezone());
				today.setToNow();
				//String theFile = today.year + "-" + today.month + "-" + today.monthDay + "_" + today.format("%k:%M:%S");
				String theFile = today.year + "-" + today.month + "-" + today.monthDay + "_" + today.hour + "-" + today.minute + "-" + today.second;
				//string theFile = "cassie";
				File direc = new File(Environment.getExternalStorageDirectory() // function to add a file storage directory
						+ "/squared/");
				if (direc.mkdir() || direc.isDirectory()) {
					file = new File(Environment.getExternalStorageDirectory()
							+ "/squared/" + theFile + ".txt");
					fw = new FileWriter(file.getAbsoluteFile());
					bw = new BufferedWriter(fw);
					pw = new PrintWriter(bw);
				}
			}
	
			String content = score + ", "; // string content to concatenate score + pw appendage
			 pw.append(content);
			 pw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/******************************************************************************/
	/* START COLOR STUFF */
	/******************************************************************************/
	public void displayColor(View view) { // public void displayColor
		TextView colorView = (TextView) findViewById(R.id.textViewColor);
		colorView.setTextColor(textColor);
		colorView.setText(nextColor_s);
	}

	public void updateColor() {  // function to make the colors alternate
		Random r = new Random(); 
		switch (r.nextInt(4)) {
		case 0:
			nextColor_s = "Red";
			nextColor = Color.parseColor("#FF0000"); // function to input color red
			break;
		case 1:
			nextColor_s = "Blue";
			nextColor = Color.parseColor("#0000FF"); // function to input color blue
			break;
		case 2:
			nextColor_s = "Yellow";
			nextColor = Color.parseColor("#FFFF00"); // function to input color yellow
			break;
		case 3:
			nextColor_s = "Green"; // function to input color green
			nextColor = Color.parseColor("#00FF00");
			break;
		}

		switch (r.nextInt(4)) { // change colors 
		case 0:
			textColor = Color.RED;
			break;
		case 1:
			textColor = Color.BLUE;
			break;
		case 2:
			textColor = Color.YELLOW;
			break;
		case 3:
			textColor = Color.GREEN;
			break;
		}
	}

	/******************************************************************************/
	/* END COLOR STUFF */
	/******************************************************************************/

	/******************************************************************************/
	/* START TIME STUFF */
	/******************************************************************************/
	public void resetTime() {
		startTime_ms = (double) System.currentTimeMillis();
		startTime_s = startTime_ms / 1000;

		previousTime_ms = startTime_ms; // reset time functions
		previousTime_s = startTime_s; // reset time functions

		currentTime_ms = startTime_ms; // currentTIme_ms
		currentTime_s = startTime_s; // currentTime_s = startTime

		elapsedTime_ms = 0; // elapsed time
		elapsedTime_s = 0;

		timeDiff_ms = 0;
		timeDiff_s = 0;
	}

	public void displayTime(View view) {
		//TextView timeView = (TextView) findViewById(R.id.textViewTime);
		//timeView.setText("Time: " + String.format("%.0f", elapsedTime_s));
		//String.format("%.2f", elapsedTime_s);
	}

	public void updateTime() {
		previousTime_ms = currentTime_ms; // function to update time
		previousTime_s = currentTime_s; // function to run the current time

		currentTime_ms = (double) System.currentTimeMillis();
		currentTime_s = currentTime_ms / 1000; // initialize the current time in seconds with milleseconds

		elapsedTime_ms = currentTime_ms - startTime_ms;
		elapsedTime_s = elapsedTime_ms / 1000;

		timeDiff_ms = currentTime_ms - previousTime_ms;
		timeDiff_s = timeDiff_ms / 1000; 
		
		TextView timeView = (TextView) findViewById(R.id.textViewTime);
		timeView.setText("Time: " + String.format("%.0f", elapsedTime_s)); // timeView.setText() // with elapsedTime_variable
		
	}

	/******************************************************************************/
	/* END TIME STUFF */
	/******************************************************************************/

	public void setButtons(View view) {

	}

	/******************************************************************************/
	/* START SCORE STUFF */
	/******************************************************************************/
	public void displayScore(View view) { // function to displayScore
		TextView scoreView = (TextView) findViewById(R.id.textViewScore);
		scoreView.setText("Score: " + String.format("%.0f", score));
		// note1: the sizeView is only for debugging, it will be removed later
		// note2: the color view needs to be set so it spans the entire width
		// TextView sizeView = (TextView) findViewById (R.id.textViewSizes);
		// sizeView.setText("Size is: " + String.format("%d", screenWidth));

	}

	public void updateScore() {
		// Higher time difference means lower modifier, lower time difference
		// means higher modifier
		// In general, modifier will go up, because elapsed time is always going
		// up
		// Divide by 10 so that the score string doesn't skew the rest of the
		// screen
		modifier = (elapsedTime_ms / timeDiff_ms / 10);
		score += modifier;
	}

	/******************************************************************************/
	/* END SCORE STUFF */
	/******************************************************************************/
	/******************************************************************************/
	/* START BUTTON ACTIONS */
	/******************************************************************************/
	public void update(View view) {
		updateColor();
		updateTime();
		updateScore(); // update score always has to be after update time,
						// because the modifier is based on timestamps

		displayColor(view);
		displayTime(view);
		displayScore(view);
	}

	public void reset(View view) { // The same as updateAll however, the score
									// is reset to 0, instead of calling
									// updateScore
		updateColor();
		updateTime();
		score = 0;

		LayoutInflater inflater = getLayoutInflater();

		View layout = inflater.inflate(R.layout.custom_toast,
				(ViewGroup) findViewById(R.id.custom_toast_layout_id));

		// set the image for the toast
		// ImageView image = (ImageView) layout.findViewById(R.id.toastImage);
		// image.setImageResource(R.drawable.ic_launcher);

		// set the message for the toast
		TextView text = (TextView) layout.findViewById(R.id.toastText);
		text.setText("Game Over!! Play Again"); // prompts the user to play again
		resetTime(); // reset the time after the time expires
		
		// create the toast
		// note: Toast is final, because the timer requires it
		final Toast toast = new Toast(getApplicationContext());
		toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(layout);
		toast.show(); // function to display toast

		// The Toast Timer
		// This will allow us to control how long the toast appears.
		// There are only 2 options for how long a toast appears: LONG and SHORT
		// However by calling toast.cancel() after a certain amount of time,
		// we can create the effect of a different time for toast duration.
		Timer t = new Timer();
		t.schedule(new TimerTask() {
			@Override
			public void run() {
				toast.cancel();
			}
		}, 500); // this is where we set the time for toast

		displayColor(view); // the color is chosen here, and displayed as output
		displayTime(view); // the time that the toasts lasts prompted on the screen
		displayScore(view); // the score is displayed here onto the screen window
	}

	public void buttonAction(View view, int button) {
		if (button != nextColor) { // button action if statement check
			reset(view); // reset the view of the button
		} else {
			writeToFile (score); // write the data to file
			update(view); // update the color of the next button
		}
	}

	public void resetButtons(View view) {

		// Get Imagebuttons
		ImageButton button1 = (ImageButton) findViewById(R.id.button1); // function to find then new button
		ImageButton button2 = (ImageButton) findViewById(R.id.button2); // function to find the new button
		ImageButton button3 = (ImageButton) findViewById(R.id.button3);
		ImageButton button4 = (ImageButton) findViewById(R.id.button4);

		// Get color int from the ImageButtons
		ColorDrawable colorButton1 = (ColorDrawable) button1.getBackground();
		int colorButton1ID = colorButton1.getColor(); // color button function
		ColorDrawable colorButton2 = (ColorDrawable) button2.getBackground();
		int colorButton2ID = colorButton2.getColor(); // function to get color from color Button2 id
		ColorDrawable colorButton3 = (ColorDrawable) button3.getBackground();
		int colorButton3ID = colorButton3.getColor(); // color button 3
		ColorDrawable colorButton4 = (ColorDrawable) button4.getBackground(); //color button 4
		int colorButton4ID = colorButton4.getColor(); // color button 4 id to change the color for get color

		// Set the new colors

		Random r = new Random(); // random call to switch the colors of buttons 
		switch (r.nextInt(6)) { // there are six cases to to this
		
		case 0: // Swap 1 and 2
			button1.setBackgroundColor(colorButton2ID); // differing cases 
			button2.setBackgroundColor(colorButton1ID); // set off by case numbers
			break; // break to the end of the switch statement
		case 1: // Swap 1 and 3
			button1.setBackgroundColor(colorButton3ID);
			button3.setBackgroundColor(colorButton1ID);
			break;
		case 2: // Swap 1 and 4
			button1.setBackgroundColor(colorButton4ID);
			button4.setBackgroundColor(colorButton1ID); // set the background color of the button
			break; // break to the end of the switch statement
		case 3: // Swap 2 and 3
			button2.setBackgroundColor(colorButton3ID);
			button3.setBackgroundColor(colorButton2ID); // set the background color of the button
			break;
		case 4: // Swap 2 and 4
			button2.setBackgroundColor(colorButton4ID);
			button4.setBackgroundColor(colorButton2ID); // set the background color of the button
			break;

		case 5: // Swap 3 and 4
			button3.setBackgroundColor(colorButton4ID);
			button4.setBackgroundColor(colorButton3ID); // set the background color of the button
			break;
		}

	}

	public void buttonPress(View view) {
		// Color buttonColor = view.getBackgroundColor();

		ColorDrawable buttonColor = (ColorDrawable) view.getBackground();
		int colorId = buttonColor.getColor(); // set the colorID to the buttoncolor and then get the color of the button

		// TextView scoreView = (TextView) findViewById(R.id.textViewScore);
		// scoreView.setText("Score: " + String.format("%d", colorId));
		buttonAction(view, colorId);

		resetButtons(view); // reset the buttons and view the final view of resetButtons

	} 

	/******************************************************************************/
	/******************************************************************************/
	/* END BUTTON ACTIONS */
	/******************************************************************************/




} // end main 
